#!/usr/bin/env python
# -*- coding: utf-8 -*-

from cStringIO import StringIO
import random
import unittest

import ws9.file


class TestIsFilelike(unittest.TestCase):
    
    class ReadFile(object):
        mode = 'r'
        close = lambda *args: None
        read = lambda *args: None
        readline = lambda *args: None
        readlines = lambda *args: None
    
    class WriteFile(object):
        mode = 'w'
        close = lambda *args: None
        write = lambda *args: None
        writelines = lambda *args: None
    
    class ReadWriteFile(object):
        mode = 'rw'
        close = lambda *args: None
        read = lambda *args: None
        readline = lambda *args: None
        readlines = lambda *args: None
        write = lambda *args: None
        writelines = lambda *args: None
    
    def testReadMode(self):
        obj = self.ReadFile()
        self.assert_(ws9.file.is_filelike(obj),
            'Cannot recognise readable objects.')
    
    def testNotReadMode(self):
        obj = self.WriteFile()
        obj.mode = 'r'
        self.failIf(ws9.file.is_filelike(obj),
            'Cannot recognise unreadable objects.')
    
    def testWriteMode(self):
        obj = self.WriteFile()
        self.assert_(ws9.file.is_filelike(obj),
            'Cannot recognise writable objects.')
    
    def testNotWriteMode(self):
        obj = self.ReadFile()
        obj.mode = 'w'
        self.failIf(ws9.file.is_filelike(obj),
            'Cannot recognise unwritable objects.')
    
    def testReadWriteMode(self):
        obj = self.ReadWriteFile()
        self.assert_(ws9.file.is_filelike(obj),
            'Cannot recognise read/write-able objects.')


class TestCopyStream(unittest.TestCase):
    
    def setUp(self):
        self.example_data = ''.join(chr(random.randint(0, 255))
            for i in xrange(65536))
        self.read_stream = StringIO(self.example_data)
        self.write_stream = StringIO()
    
    def testIntegrity(self):
        ws9.file.copy_stream(self.read_stream, self.write_stream,
            chunk_size=8192)
        self.assertEqual(self.write_stream.getvalue(), self.example_data)
    
    def tearDown(self):
        self.read_stream.close(), self.write_stream.close()



if __name__ == '__main__':
    unittest.main()
